package com.cloud.service.impl;

import com.cloud.entity.PageInfo;
import com.cloud.entity.Provider;
import com.cloud.mapper.ProviderMapper;
import com.cloud.service.ProviderService;
import com.cloud.utils.GlobalConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author .
 * created in 2020/1/12 17:44
 */

@Service
public class ProviderServiceImpl implements ProviderService {

    private Logger logger = LoggerFactory.getLogger(ProviderServiceImpl.class);

    private ProviderMapper providerMapper;

    public ProviderServiceImpl(ProviderMapper providerMapper) {
        this.providerMapper = providerMapper;
    }

    @Override
    public int addProvider(Provider provider) {
        Date curDate = new Date();
        provider.setStatus(1);
        provider.setCtime(curDate);
        provider.setUtime(curDate);
        int result = providerMapper.addProvider(provider);
        if (result > 0) {
            logger.info("供应商【{}】信息已添加成功", provider.getName());
            return GlobalConstant.SUCCESS;
        }
        logger.info("供应商【{}】信息添加失败", provider.getName());
        return GlobalConstant.ERROR;
    }

    @Override
    public int delProvider(String id) {
        if (id.contains(",")) {
            String[] idList = id.split(",");
            List<Integer> ids = new ArrayList<>();
            for (String s : idList) {
                ids.add(Integer.parseInt(s));
            }
            int result = providerMapper.delProviders(ids);
            return result == idList.length ? GlobalConstant.SUCCESS : GlobalConstant.ERROR;
        }
        return providerMapper.delProvider(Integer.parseInt(id));
    }

    @Override
    public int updateProvider(Provider provider) {
        int result = providerMapper.updateProvider(provider);
        if (result > 0) {
            logger.info("供应商【{}】信息更新成功!", provider.getName());
            return GlobalConstant.SUCCESS;
        }
        logger.info("供应商【{}】信息更新失败!", provider.getName());
        return GlobalConstant.ERROR;
    }

    @Override
    public Provider findById(int id) {
        return providerMapper.findById(id);
    }

    @Override
    public Provider findByName(String name) {
        return providerMapper.findByName(name);
    }

    @Override
    public PageInfo<Provider> findAll(PageInfo<Provider> info, String name) {
        if (StringUtils.isEmpty(name)) name = null;
        info.setCount(providerMapper.getProviderCount(name));
        info.setData(providerMapper.findAllByPage((info.getPage() - 1) * info.getLimit(), info.getLimit(), name));
        return info;
    }
}
